<template>
  <div class="maintenance-page">
    <!-- Statistics Cards -->
    <div class="stat-cards">
      <el-row :gutter="20">
        <el-col :span="6" v-for="stat in statistics" :key="stat.title">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-icon" :style="{ backgroundColor: stat.bgColor }">
              <el-icon><component :is="stat.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-title">{{ stat.title }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- Main Content -->
    <div class="main-content">
      <el-row :gutter="20">
        <!-- Left: Chart Section -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <h3>维护记录统计</h3>
                <el-radio-group v-model="chartTimeRange" size="small">
                  <el-radio-button label="week">本周</el-radio-button>
                  <el-radio-button label="month">本月</el-radio-button>
                  <el-radio-button label="year">本年</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div class="chart-container" ref="chartRef"></div>
          </el-card>
        </el-col>

        <!-- Right: Quick Actions -->
        <el-col :span="12">
          <el-card class="quick-actions">
            <template #header>
              <div class="card-header">
                <h3>快速操作</h3>
              </div>
            </template>
            <div class="action-grid">
              <div
                v-for="action in quickActions"
                :key="action.title"
                class="action-item"
                @click="action.handler"
              >
                <el-icon><component :is="action.icon" /></el-icon>
                <span>{{ action.title }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- Maintenance Records Table -->
    <el-card class="records-table">
      <template #header>
        <div class="table-header">
          <div class="left">
            <h3>维护记录列表</h3>
            <el-tag type="success">共 {{ total }} 条记录</el-tag>
          </div>
          <div class="right">
            <el-input
              v-model="searchQuery"
              placeholder="搜索维护记录"
              prefix-icon="Search"
              class="search-input"
            />
            <el-button type="primary" @click="handleAddRecord">
              <el-icon><Plus /></el-icon>新增记录
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredRecords" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="记录ID" width="100" />
        <el-table-column prop="robotId" label="机器人" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.robotId }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="维护类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getMaintenanceTypeTag(row.type)">{{
              row.type
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="maintainer" label="维护人员" width="120" />
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="duration" label="耗时" width="100" />
        <el-table-column
          prop="description"
          label="描述"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button link type="primary" @click="handleDetails(row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- Add/Edit Record Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增维护记录' : '编辑维护记录'"
      width="50%"
    >
      <el-form
        ref="recordForm"
        :model="recordForm"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="机器人" prop="robotId">
          <el-select
            v-model="recordForm.robotId"
            placeholder="选择机器人"
            class="w-full"
          >
            <el-option
              v-for="robot in robots"
              :key="robot.id"
              :label="robot.name"
              :value="robot.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维护类型" prop="type">
          <el-select
            v-model="recordForm.type"
            placeholder="选择维护类型"
            class="w-full"
          >
            <el-option
              v-for="type in maintenanceTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="recordForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="维护时长" prop="duration">
          <el-input-number
            v-model="recordForm.duration"
            :min="1"
            :max="999"
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="维护人员" prop="maintainer">
          <el-input
            v-model="recordForm.maintainer"
            placeholder="输入维护人员"
          />
        </el-form-item>
        <el-form-item label="维护描述" prop="description">
          <el-input
            v-model="recordForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入维护描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// Statistics data
const statistics = ref([
  {
    title: '本月维护次数',
    value: '48',
    icon: 'Tools',
    bgColor: '#4834d4'
  },
  {
    title: '待处理维护',
    value: '5',
    icon: 'Warning',
    bgColor: '#eb3b5a'
  },
  {
    title: '完成率',
    value: '96%',
    icon: 'Check',
    bgColor: '#20bf6b'
  },
  {
    title: '平均维护时长',
    value: '2.5h',
    icon: 'Setting',
    bgColor: '#0fb9b1'
  }
])

// Quick actions
const quickActions = [
  {
    title: '新增记录',
    icon: 'Plus',
    handler: () => handleAddRecord()
  },
  {
    title: '导出记录',
    icon: 'Download',
    handler: () => handleExport()
  },
  {
    title: '导入记录',
    icon: 'Upload',
    handler: () => handleImport()
  },
  {
    title: '刷新数据',
    icon: 'Refresh',
    handler: () => refreshData()
  }
]

// Chart
const chartRef = ref(null)
const chartTimeRange = ref('week')
let chart = null

// Table data
const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const toal = ref(100)

const records = ref([
  {
    id: 'M001',
    robotId: 'R001',
    type: '定期保养',
    status: '已完成',
    maintainer: '张工',
    startTime: '2025-02-10 09:00:00',
    duration: '2h',
    description: '例行检查和保养'
  }
  // ... more records
])

// Computed
const filteredRecords = computed(() => {
  return records.value.filter(
    (record) =>
      record.id.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      record.robotId.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      record.maintainer.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// Form data
const dialogVisible = ref(false)
const dialogType = ref('add')
const recordForm = ref({
  robotId: '',
  type: '',
  startTime: '',
  duration: 1,
  maintainer: '',
  description: ''
})

const rules = {
  robotId: [{ required: true, message: '请选择机器人', trigger: 'change' }],
  type: [{ required: true, message: '请选择维护类型', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  maintainer: [{ required: true, message: '请输入维护人员', trigger: 'blur' }]
}

// Options data
const robots = ref([
  { id: 'R001', name: '机器人A' },
  { id: 'R002', name: '机器人B' }
])

const maintenanceTypes = [
  { label: '定期保养', value: 'regular' },
  { label: '故障维修', value: 'repair' },
  { label: '升级更新', value: 'upgrade' },
  { label: '检查校准', value: 'calibration' }
]

// Methods
const initChart = () => {
  if (chartRef.value) {
    chart = echarts.init(chartRef.value)
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['维护次数', '平均时长']
      },
      xAxis: {
        type: 'category',
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      },
      yAxis: [
        {
          type: 'value',
          name: '次数',
          position: 'left'
        },
        {
          type: 'value',
          name: '时长(h)',
          position: 'right'
        }
      ],
      series: [
        {
          name: '维护次数',
          type: 'bar',
          data: [10, 8, 12, 9, 11, 7, 6],
          itemStyle: {
            color: '#4834d4'
          }
        },
        {
          name: '平均时长',
          type: 'line',
          yAxisIndex: 1,
          data: [2.5, 2.1, 3.0, 2.8, 2.6, 2.3, 2.0],
          itemStyle: {
            color: '#20bf6b'
          }
        }
      ]
    }
    chart.setOption(option)
  }
}

const handleAddRecord = () => {
  dialogType.value = 'add'
  recordForm.value = {
    robotId: '',
    type: '',
    startTime: '',
    duration: 1,
    maintainer: '',
    description: ''
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  recordForm.value = { ...row }
  dialogVisible.value = true
}

const handleDetails = (row) => {
  ElMessage.success(`查看记录：${row.id}`)
}

const handleSubmit = () => {
  ElMessage.success('提交成功')
  dialogVisible.value = false
}

const handleExport = () => {
  ElMessage.success('导出成功')
}

const handleImport = () => {
  ElMessage.success('导入成功')
}

const refreshData = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('数据已刷新')
  }, 1000)
}

const getMaintenanceTypeTag = (type) => {
  const types = {
    定期保养: 'success',
    故障维修: 'danger',
    升级更新: 'warning',
    检查校准: 'info'
  }
  return types[type] || 'info'
}

const getStatusTag = (status) => {
  const types = {
    已完成: 'success',
    进行中: 'primary',
    待处理: 'warning',
    已取消: 'info'
  }
  return types[status] || 'info'
}

// Lifecycle
onMounted(() => {
  initChart()
  window.addEventListener('resize', () => {
    chart?.resize()
  })
})

// Clean up
onUnmounted(() => {
  window.removeEventListener('resize', () => {
    chart?.resize()
  })
  chart?.dispose()
})
</script>

<style lang="scss" scoped>
.maintenance-page {
  padding: 20px;

  .stat-cards {
    margin-bottom: 20px;

    .stat-card {
      height: 100px;

      .stat-icon {
        float: left;
        width: 64px;
        height: 64px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;

        .el-icon {
          font-size: 24px;
          color: white;
        }
      }

      .stat-info {
        overflow: hidden;

        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
          line-height: 1.5;
        }

        .stat-title {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }

  .main-content {
    margin-bottom: 20px;

    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        h3 {
          margin: 0;
          font-size: 16px;
        }
      }

      .chart-container {
        height: 350px;
      }
    }

    .quick-actions {
      height: 100%;

      .card-header {
        h3 {
          margin: 0;
          font-size: 16px;
        }
      }

      .action-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;
        padding: 16px;

        .action-item {
          height: 100px;
          background-color: #f5f7fa;
          border-radius: 8px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            background-color: #ecf5ff;
            color: #4834d4;
          }

          .el-icon {
            font-size: 24px;
            margin-bottom: 8px;
          }

          span {
            font-size: 14px;
          }
        }
      }
    }
  }

  .records-table {
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .left {
        display: flex;
        align-items: center;
        gap: 12px;

        h3 {
          margin: 0;
          font-size: 16px;
        }
      }

      .right {
        display: flex;
        gap: 12px;

        .search-input {
          width: 300px;
        }
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

// Dialog
.dialog-foote {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// Custom theme color
:deep(.el-button--primary) {
  --el-button-bg-color: #4834d4;
  --el-button-border-color: #4834d4;
  --el-button-hover-bg-color: #5b48e5;
  --el-button-hover-border-color: #5b48e5;
  --el-button-active-bg-color: #3f2db8;
  --el-button-active-border-color: #3f2db8;
}

:deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
  background-color: #4834d4;
  border-color: #4834d4;
}

// Responsive
@media screen and (max-width: 768px) {
  .maintenance-page {
    .main-content {
      .el-row {
        margin: 0 !important;
      }

      .el-col {
        padding: 0 !important;
        margin-bottom: 20px;
      }
    }

    .records-table {
      .table-header {
        flex-direction: column;
        gap: 12px;
        align-items: stretch;

        .right {
          flex-direction: column;

          .search-input {
            width: 100%;
          }
        }
      }
    }
  }
}
</style>
